package com.shangcg.Alearn.mythread.multi;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

/**
 * 自定义同步组件：
 *  该工具实现，在同一时刻至多允许两个线程同时访问，超过两个线程将会被阻塞
 * @author: shangcg
 * @create: 2021-10-19 22:26
 */
public class TwinsLock implements Lock {

    private final Sync sync = new Sync(2);
    static final class Sync extends AbstractQueuedSynchronizer{
        Sync(int count){
            if (count < 0){

            }
            setState(count);
        }

        public int tryAcquireShared(int count){
            for (;;){
                int current = getState();
                int newCount = current - count;
                if (newCount < 0 || compareAndSetState(current, newCount)){
                    return newCount;
                }
            }
        }

        public boolean tryReleaseShared(int returnCount){
            for (;;){
                int current = getState();
                int newCount = current + returnCount;
                if (compareAndSetState(current, newCount)){
                    return true;
                }
            }
        }
    }



    @Override
    public void lock() {
        sync.acquireShared(1);
    }

    @Override
    public void lockInterruptibly() throws InterruptedException {

    }

    @Override
    public boolean tryLock() {
        return false;
    }

    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return false;
    }

    @Override
    public void unlock() {
        sync.releaseShared(1);
    }

    @Override
    public Condition newCondition() {
        return null;
    }
}